package cn.woo5.wechat.open.study.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.jcabi.aspects.Loggable;

import cn.woo5.wechat.open.study.util.CipherUtil;
import cn.woo5.wechat.open.study.util.Config;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping(value = "/")
@Slf4j
public class ValidationController {

  @Autowired
  private CipherUtil cipherUtil;
  @Autowired
  private Config config;

  // TODO loggable
  @Loggable
  @RequestMapping(value = "/", method = { RequestMethod.GET })
  public String validate(@RequestParam final String signature, @RequestParam final String timestamp,
      @RequestParam final String nonce, @RequestParam final String echostr) {
    log.debug("{},{},{},{}", signature, timestamp, nonce, echostr);
    boolean fromWeixin = cipherUtil.weixinSignCheck(signature, nonce, timestamp, config.getWeixinToken());
    return fromWeixin ? echostr : null;
  }

}

